package org.zpengblog.cosdemo.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.zpengblog.cosdemo.domain.Result;
import org.zpengblog.cosdemo.domain.SoupDto;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * 获取每日鸡汤.
 *
 * @author linzp
 * @version 1.0.0
 * CreateDate 2021/1/21 10:19
 */
@RestController
@Slf4j
public class ChickenSoupController {

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping("getChickenSoup")
    private Result getSoup() {

        Map<String, Object> params = new HashMap<>();
        HttpEntity<Map<String, Object>> request = new HttpEntity<>(params);
        ResponseEntity<SoupDto> result = restTemplate.exchange("https://data.zhai78.com/openOneBad.php", HttpMethod.GET, request, SoupDto.class);
        log.info("请求鸡汤结果 result={}", result);
        HttpStatus statusCode = result.getStatusCode();
        if (statusCode.equals(HttpStatus.OK)) {
            SoupDto body = result.getBody();
            if (Objects.nonNull(body) && body.getStatus() == 1) {
                return Result.success(body.getTxt());
            }
            return Result.failure("这碗鸡汤不行，再换一碗");
        }

        return Result.failure("鸡汤喝完了");
    }

    /**
     * 偷别人的鸡汤.
     *
     * @return
     */
    @RequestMapping("/doSomeThingBad")
    private Result stealOthersSoup() {

        long start = System.currentTimeMillis();
        List<String> soupList = getSoupList();
        log.warn("偷取鸡汤消耗时间 {} ms", System.currentTimeMillis() - start);

        long start2 = System.currentTimeMillis();
        boolean b = false;
        try {
            b = intoTxt(soupList);
        } catch (Exception e) {
            log.error("鸡汤写入文件失败了。。。");
            return Result.failure("写入文件失败");
        }
        log.warn("存放鸡汤消耗的时间= {} ms", System.currentTimeMillis() - start2);
        log.warn("偷取鸡汤消耗总时长 【{}】秒", (System.currentTimeMillis() - start)/1000);
        return Result.success();
    }

    private List<String> getSoupList() {

        List<String> soupResults = new ArrayList<>(10000);

        HttpEntity<Map<String, Object>> request = new HttpEntity<>(new HashMap<>(0));

        //准备偷一万碗！！
        for (int i = 0; i < 100; i++) {
            try {
                //累了，休息一下
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            ResponseEntity<String> result;
            try {
//                result = restTemplate.exchange("https://data.zhai78.com/openOneBad.php", HttpMethod.GET, request, SoupDto.class);
                result = restTemplate.exchange("https://du.shadiao.app/api.php", HttpMethod.GET, request, String.class);
            }catch (Exception e){
                log.error("偷鸡汤失败了，汤碗都被打翻 T_T........");
                continue;
            }
            HttpStatus statusCode = result.getStatusCode();
            if (statusCode.equals(HttpStatus.OK)) {
                log.info("偷鸡汤成功啦！！！response = {}", result);
//                SoupDto body = result.getBody();
                String body = result.getBody();
                if (Objects.nonNull(body)) {
                    soupResults.add(body);
                } else {
                    log.error("请求鸡汤失败！");
                }
            }
        }

        log.info("总共偷取的鸡汤数量 soup = {} 碗", soupResults.size());
        //一样的鸡汤我不要！
        Set<String> strings = new HashSet<>(soupResults);
        log.info("剔除同样的鸡汤后的剩余鸡汤数量 after_soup = {} 碗", strings.size());

        //返回去重结果
        return new ArrayList<>(strings);
    }

    /**
     * 鸡汤存入txt文件.
     *
     * @param soupList 鸡汤列表.
     * @return
     */
    private boolean intoTxt(List<String> soupList) throws Exception {

        if (soupList.isEmpty()) {
            return false;
        }
        log.info("鸡汤数量：【{}】 碗", soupList.size());

        String filePath = ChickenSoupController.class.getResource("/").getPath() + "soup2.txt";
        File file = new File(filePath);

        boolean exists = file.exists();
        if (!exists) {
            file.createNewFile();
        }

        FileWriter fileWriter;
        try {
            fileWriter = new FileWriter(file, true);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }

        soupList.stream().forEach(item -> {
            try {
                fileWriter.write(item + "\n");
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        fileWriter.flush();
        fileWriter.close();
        log.info("鸡汤写入文件结束.......");
        return true;
    }
}
